package Emailhandler;
import OBSXML.MailServerConf;
import java.io.File;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import java.util.Properties;

/**
 * En implementation af Mailer som bruger Google's e-mailserver til, at sende e-mails.
 *
 * @author Daniel Koch
 */
public class GmailMailer implements Mailer {
    private Properties props = new Properties();
    private String username;
    private String password;
    private String fromEmailName;

    // Indlæs værdiern fra mailserverkonfigurationsfilen
    private MailServerConf msc = new MailServerConf(File.separator+"app_config"+File.separator, "MailServer.xml");

    /**
     * Initialiserer GmailMailer
     */
    public GmailMailer() {
        this.username = msc.getMailUsername();
        this.password = msc.getMailPassword();
        this.fromEmailName = msc.getMailFromName() + "<" + msc.getMailFromEmail() + ">";
        this.props.put("mail.smtp.host", msc.getMailHost());
	this.props.put("mail.smtp.auth", "true");
	this.props.put("mail.smtp.port", Integer.toString(msc.getMailPort()));
	this.props.put("mail.smtp.socketFactory.port", Integer.toString(msc.getMailPort()));
	this.props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
	this.props.put("mail.smtp.socketFactory.fallback", "false");
        this.props.setProperty("mail.transport.protocol", msc.getMailProtocol());
	this.props.setProperty("mail.smtp.quitwait", "false");
    }

    /**
     * Sender en e-mail.
     *
     * @param recipients
     * @param subject
     * @param message
     * @throws Exception
     */
    public void sendMail(String[] recipients, String subject, String message) throws Exception {
        Session session = Session.getDefaultInstance(this.props, new MailerAuth(this.username, this.password));
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(this.fromEmailName));

        // Konverter alle e-mailadresser fra String til InternetAddress-objekter
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }

        msg.setRecipients(Message.RecipientType.BCC, addressTo);
        msg.setSubject(subject);
        msg.setContent(message, "text/html");
        Transport.send(msg);
    }
}
